package com.t365.qmm.service.impl;

import com.t365.qmm.mapper.ClassifyMapper;
import com.t365.qmm.pojo.Classify;
import com.t365.qmm.service.ClassifyService;
import com.t365.qmm.utils.MyabtisUtil;
import org.apache.ibatis.session.SqlSession;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ClassifyServiceImpl implements ClassifyService {
 
    @Override
    public List<Classify> getAllClassifyList(Map<String,String> maps) throws SQLException {

        SqlSession session= MyabtisUtil.createSqlSession();
        //获取所有的分类列表
        List<Classify> list = session.getMapper(ClassifyMapper.class).getAllByCondition(maps);

        //递归获取子分类列表
        List<Classify> menuList = list.stream().filter(subMenu ->subMenu.getParentId().equals(0))
                          .map(subMenu -> {subMenu.setMenuList(getChildren(subMenu,list)); return  subMenu;})
                          .collect(Collectors.toList());

        MyabtisUtil.closeSqlSession(session);
        return menuList;
    }

    private List<Classify> getChildren(Classify root,List<Classify> allList){
        List<Classify> entities = allList.stream().filter(subMenu -> subMenu.getParentId().equals(root.getId()))
                                                                    .map(subMenu ->{subMenu.setMenuList(getChildren(subMenu,allList)); return subMenu;})
                                                                    .collect(Collectors.toList());
        return entities;
    }
}
